package com.htthorizon.system.aop;

import com.htthorizon.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @author Brilliant
 */
@Component
@Aspect
@Slf4j
public class ControllerAop {

    private Date beforeDate;
    private Date afterDate;

    @Autowired
    private RedisService redisService;

    @Pointcut("execution(* com.htthorizon.system.controller..*.*(..))")
    public void pointcut() {

    }

    @Before("pointcut()")
    public void beforeAdvice() {
        beforeDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(beforeDate);
    }

    @After("pointcut()")
    public void afterAdvice() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        afterDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(afterDate);
        long time = (afterDate.getTime() - beforeDate.getTime()) ;

        this.addUserRecord(time);

        log.info("{} => 执行时长(单位/毫秒)：{}", request.getRequestURI(), time);
    }

    private void addUserRecord(Long time) {
        synchronized (ControllerAop.class){
           redisService.setCacheObject("BusinessSystemResponseTime",time);
        }
    }


}
